<template>
  <div class="customer-container">
    <div class="create-project">
      <h1 class="page-title">{{ mode === 'edit' ? '编辑项目' : '创建项目' }}</h1>

      <!-- 基本信息部分 -->
      <div class="basic-info-wrapper">
        <el-card class="basic-info-card" :body-style="{ padding: '30px' }">
          <el-row :gutter="40">
            <!-- 左侧表单 -->
            <el-col :span="12">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicFormRules"
                label-position="left"
                label-width="100px"
              >
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="basicForm.projectName" />
                </el-form-item>

                <el-form-item label="活动时间" prop="activityTime">
                  <el-date-picker
                    v-model="basicForm.activityTime"
                    type="datetimerange"
                    range-separator="——"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="MM月DD日 HH:mm"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :clearable="true"
                    :editable="false"
                    :locale="locale"
                    style="width: 100%"
                  />
                </el-form-item>

                <el-form-item label="工作地点" prop="workLocation">
                  <el-input v-model="basicForm.workLocation" />
                </el-form-item>
              </el-form>
            </el-col>

            <!-- 右侧项目归属 -->
            <el-col :span="12">
              <el-form
                ref="scheduleFormRef"
                :model="scheduleForm"
                :rules="scheduleFormRules"
                label-position="top"
              >
                <!-- 空白占位符，与左侧"项目名称"对齐 -->
                <el-form-item style="height: 32px; margin-bottom: 20px"></el-form-item>

                <!-- 项目归属，与左侧"活动时间"对齐 -->
                <el-form-item label="选择项目归属：" prop="projectBelong" class="compact-form-item">
                  <el-select
                    v-model="scheduleForm.projectBelong"
                    placeholder="请选择项目归属"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="customer in customerList"
                      :key="customer.rowid"
                      :label="customer['686f26e30323e30ac5121f7e']"
                      :value="customer['686f26e30323e30ac5121f7e']"
                    />
                  </el-select>
                </el-form-item>

                <!-- 空白占位符，与左侧"工作地点"对齐 -->
                <el-form-item style="height: 32px; margin-bottom: 20px"></el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>

        <!-- 保存按钮在卡片外左下角 -->
        <el-button type="primary" class="save-project-btn" @click="handleSaveProject"
          >保存项目信息</el-button
        >
      </div>

      <!-- 分隔线 -->
      <div class="divider-line"></div>

      <!-- 角色信息部分 -->
      <el-row :gutter="25" class="roles-section">
        <!-- 动态角色卡片 -->
        <el-col :span="8" v-for="(role, index) in roles" :key="index">
          <el-card class="role-card" :body-style="{ padding: '15px' }">
            <div class="role-header">
              <el-button
                type="danger"
                size="small"
                circle
                @click="removeRole(index)"
                v-if="roles.length > 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-form
              :ref="
                (el) => {
                  if (el) roleFormRefs[index] = el
                }
              "
              :model="role"
              :rules="getRoleFormRules(index)"
              label-position="left"
              label-width="140px"
            >
              <el-form-item label="角色" prop="roleType">
                <el-select
                  v-model="role.roleType"
                  placeholder="请选择角色类型"
                  style="width: 100%"
                  @change="handleRoleTypeChange(index)"
                >
                  <el-option
                    v-for="option in getAvailableRoleOptions(index)"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="需求人数" prop="personCount" v-if="role.roleType !== '带队'">
                <el-input
                  v-model="role.personCount"
                  type="number"
                  :min="1"
                  placeholder="请输入需求人数（≥1）"
                  @input="handlePersonCountChange(index)"
                />
              </el-form-item>

              <el-form-item
                label="最少提交人数"
                prop="minSubmitCount"
                v-if="role.roleType !== '带队'"
              >
                <el-input
                  v-model="role.minSubmitCount"
                  type="number"
                  :min="1"
                  :placeholder="`最少${role.personCount || 1}人`"
                  @input="handleMinSubmitCountChange(index)"
                />
              </el-form-item>

              <el-form-item label="要求" prop="requirement">
                <el-select
                  v-model="role.requirement"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入要求"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in label"
                    :key="item['68afcbe26b50e0d4f7a76785']"
                    :label="item['68afcbe26b50e0d4f7a76785']"
                    :value="item['68afcbe26b50e0d4f7a76785']"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="其它要求" prop="basicRequirement">
                <el-input type="textarea" :rows="2" v-model="role.basicRequirement" />
              </el-form-item>

              <el-form-item label="工作内容" prop="workContent">
                <el-input type="textarea" :rows="3" v-model="role.workContent" />
              </el-form-item>

              <el-form-item label="薪资" prop="salary">
                <el-input v-model="role.salary" />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 添加角色按钮 -->
        <el-col :span="8" v-if="roles.length < 3">
          <div class="add-role-card" @click="addRole">
            <div class="add-role-content">
              <el-icon class="add-role-icon"><Plus /></el-icon>
              <span class="add-role-text">添加角色</span>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 底部提交按钮 -->
      <div class="submit-section">
        <el-button type="primary" class="submit-btn" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Plus, Delete } from '@element-plus/icons-vue'
import { ref, watch, nextTick, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { apiService, ApiService } from '@/utils/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const locale = zhCn

// 路由与模式
const route = useRoute()
const router = useRouter()
const mode = ref('create') // create | edit
const editProject = ref(null)

const getCustomer = async () => {
  const customerRes = await apiService.getCustomer({ rowid: userRowId.value })
  console.log('获取客户')
  console.log(JSON.parse(customerRes.data))
  console.log(JSON.parse(customerRes.data)[0]['686f26e30323e30ac5121f7e'])

  // 将客户数据保存到 customerList 中
  customerList.value = JSON.parse(customerRes.data)
}

const getRoleArr = async () => {
  const res = await apiService.getDemand({
    rowid: editProject.value['rowid'],
  })
  console.log('需求明细')
  console.log(res)
}

onMounted(async () => {
  getLabel()
  getCustomer()
  if (route.query.id) {
    try {
      const result = await apiService.getRowById({
        rowId: route.query.id,
        worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
      })
      editProject.value = result
      mode.value = 'edit'
      console.log('进入编辑模式，项目对象:', editProject.value)

      getRoleArr()

      // 将项目数据回填到表单（按现有字段映射）
      basicForm.value.projectName = editProject.value['686df5d4fa20ded33c042478'] || ''

      // 处理项目归属（客户信息）
      try {
        const customerData = editProject.value['686f297f781faa1ac7bbda20']
        if (customerData && customerData !== '[]') {
          const parsedData = JSON.parse(customerData)
          if (parsedData && parsedData.length > 0) {
            const sourceValue = JSON.parse(parsedData[0].sourcevalue)
            scheduleForm.value.projectBelong = sourceValue['686f26e30323e30ac5121f7e'] || ''
          }
        }
      } catch (error) {
        console.error('解析客户数据失败:', error)
        scheduleForm.value.projectBelong = ''
      }

      const start = editProject.value['686e317ee9211671b47589db']
      const end = editProject.value['686f5c562307310db1c4eea1']
      if (start && end) {
        basicForm.value.activityTime = [start, end]
      }
      basicForm.value.workLocation = editProject.value['6876ff515d31544df2c58975'] || ''

      // 编辑模式进入后，拉取需求明细
      getDemand()
    } catch (e) {
      console.warn('解析编辑项目失败，退回创建模式:', e)
      mode.value = 'create'
    }
  }

  // 创建模式：恢复本地并尝试拉取需求（若有逻辑依赖可保留）
  if (mode.value !== 'edit') {
    loadSavedProjectData()
    getDemand()
  }

  // 延迟启用验证，避免页面加载时自动验证
  setTimeout(() => {
    validationEnabled.value = true
  }, 100)
})

const label = ref([])

// 表单引用
const basicFormRef = ref()
const scheduleFormRef = ref()
const roleFormRefs = ref([]) // 新增：用于存储角色表单的引用

// 基本信息表单数据
const basicForm = ref({
  projectName: '',
  activityTime: '',
  workLocation: '',
})

const getLabel = async () => {
  const res = await apiService.submitWebhook('NjhiMjVmMDA4NmE5YWEzYjE0ZDQwNDJj', {
    data: 'nullData',
  })
  console.log('获取标签')
  console.log(JSON.parse(res.data))
  console.log('标签内容:', JSON.parse(res.data)[0]['68afcbe26b50e0d4f7a76785'])

  label.value = JSON.parse(res.data)
}

const demand = ref([])

// 客户列表数据
const customerList = ref([])

// 项目归属表单数据
const scheduleForm = ref({
  projectBelong: '',
})

// 获取用户状态管理实例
const userStore = useUserStore()

// 从用户状态管理中获取真实的userRowId
const userRowId = ref(userStore.userRowid || '')

// 读取本地存储的项目数据
const loadSavedProjectData = () => {
  try {
    const savedData = localStorage.getItem('savedProjectData')
    if (savedData) {
      const parsedData = JSON.parse(savedData)

      // 恢复基本信息
      if (parsedData.basicInfo) {
        basicForm.value.projectName = parsedData.basicInfo.projectName || ''
        basicForm.value.activityTime = parsedData.basicInfo.activityTime || ''
        basicForm.value.workLocation = parsedData.basicInfo.workLocation || ''
      }

      // 恢复项目归属
      if (parsedData.projectBelong) {
        scheduleForm.value.projectBelong = parsedData.projectBelong || ''
      }

      // 恢复角色信息
      if (parsedData.roles && parsedData.roles.length > 0) {
        // 确保旧数据兼容性，为缺少的字段添加默认值
        roles.value = parsedData.roles.map((role) => ({
          roleType: role.roleType || '',
          personCount: role.personCount || '',
          minSubmitCount: role.minSubmitCount || '',
          requirement: role.requirement || '',
          basicRequirement: role.basicRequirement || '',
          workContent: role.workContent || '',
          salary: role.salary || '',
        }))

        // 检查是否有重复的角色类型，如果有则清空重复的
        const usedTypes = new Set()
        roles.value.forEach((role, index) => {
          if (role.roleType && usedTypes.has(role.roleType)) {
            // 发现重复，清空当前角色类型
            role.roleType = ''
          } else if (role.roleType) {
            usedTypes.add(role.roleType)
          }
        })
      }

      console.log('已从本地存储恢复项目数据:', parsedData)
    }
  } catch (error) {
    console.error('读取本地存储数据失败:', error)
  }
}

const getDemand = async () => {
  // 优先使用编辑模式传入的项目 rowid
  const rowid = mode.value === 'edit' && editProject.value ? editProject.value['rowid'] : null
  if (!rowid) {
    console.log('当前为创建模式或无有效rowid，跳过获取需求明细')
    return
  }

  try {
    const registerRes = await apiService.getDemand({ rowid })
    console.log('获取需求明细')
    console.log('原始响应:', registerRes)

    let demandData = []
    if (registerRes.data) {
      if (typeof registerRes.data === 'string') {
        try {
          demandData = JSON.parse(registerRes.data)
        } catch (e) {
          console.error('解析JSON字符串失败:', e)
          demandData = registerRes.data
        }
      } else if (typeof registerRes.data === 'object') {
        demandData = registerRes.data
      } else {
        demandData = registerRes.data
      }
    }

    if (Array.isArray(demandData) && demandData.length > 0) {
      // 将需求明细数据转换为角色数据格式，正确映射字段
      roles.value = demandData.map((item) => ({
        roleType: item['686f2308f11e0126aeb367d7'] || '', // 角色类型
        personCount: item['686e48ea1f42f2639e1b907b'] || '', // 需求人数
        minSubmitCount: item['686e48ea1f42f2639e1b907c'] || '', // 最少提交人数
        requirement: item['6880ba578c409b88b851aa8b'] || '', // 要求（数组，需要处理）
        basicRequirement: item['686e48ea1f42f2639e1b907e'] || '', // 其他要求
        workContent: item['686e48ea1f42f2639e1b907f'] || '', // 工作内容
        salary: item['688d889e8741e5dc9b0952d1'] || '', // 薪资
      }))

      // 处理要求字段，将数组转换为字符串
      roles.value.forEach((role) => {
        if (role.requirement && Array.isArray(role.requirement)) {
          role.requirement = role.requirement.join('、')
        }
      })

      console.log('转换后的角色数据:', roles.value)
    } else {
      console.log('未获取到有效的需求明细数据')
    }

    demand.value = demandData
  } catch (error) {
    console.error('获取需求明细失败:', error)
    ElMessage({
      message: '获取需求明细失败，请重试',
      type: 'error',
      duration: 3000,
    })
  }
}

// 页面加载时自动读取本地存储的数据（仅创建模式）
// onMounted(() => {
//   if (mode.value !== 'edit') {
//     loadSavedProjectData()
//     getDemand()
//   }
// })

// 基本信息表单校验规则
const basicFormRules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  workLocation: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
}

// 项目归属表单校验规则
const scheduleFormRules = {
  projectBelong: [{ required: false, message: '请输入项目归属', trigger: 'blur' }],
}

// 角色选项定义
const roleOptions = [
  { label: '礼仪', value: '礼仪' },
  { label: '兼职', value: '兼职' },
  { label: '带队', value: '带队' },
]

// 自定义校验函数：验证最少提交人数必须大于等于需求人数
const validateMinSubmitCount = (rule, value, callback, roleIndex) => {
  if (!value) {
    callback()
    return
  }

  const currentRole = roles.value[roleIndex]
  const personCount = parseInt(currentRole.personCount)
  const minSubmitCount = parseInt(value)

  if (isNaN(minSubmitCount)) {
    callback(new Error('最少提交人数必须是数字'))
    return
  }

  if (minSubmitCount < 1) {
    callback(new Error('最少提交人数必须大于等于1'))
    return
  }

  if (personCount && minSubmitCount < personCount) {
    callback(new Error('最少提交人数必须大于等于需求人数'))
    return
  }

  callback()
}

// 自定义校验函数：验证需求人数
const validatePersonCount = (rule, value, callback, roleIndex) => {
  if (!value) {
    callback()
    return
  }

  const personCount = parseInt(value)
  if (isNaN(personCount) || personCount < 1) {
    callback(new Error('需求人数必须大于等于1'))
    return
  }

  // 检查最少提交人数是否满足要求
  const currentRole = roles.value[roleIndex]
  const minSubmitCount = parseInt(currentRole.minSubmitCount)

  if (minSubmitCount && minSubmitCount < personCount) {
    callback(new Error('需求人数不能大于最少提交人数'))
    return
  }

  callback()
}

// 角色表单校验规则
const getRoleFormRules = (roleIndex) => {
  const currentRole = roles.value[roleIndex]
  const isTeamLeader = currentRole && currentRole.roleType === '带队'

  // 如果验证未启用，返回空规则
  if (!validationEnabled.value) {
    return {}
  }

  return {
    roleType: [{ required: true, message: '请选择角色类型', trigger: 'submit' }],
    personCount: [
      {
        required: !isTeamLeader,
        message: '请输入当前需求人数',
        trigger: 'submit',
      },
      {
        validator: (rule, value, callback) => {
          if (isTeamLeader) {
            callback()
            return
          }
          // 基本验证：必须是数字且大于等于1
          if (value && (isNaN(value) || parseInt(value) < 1)) {
            callback(new Error('需求人数必须大于等于1'))
          } else {
            callback()
          }
        },
        trigger: 'submit',
      },
    ],
    minSubmitCount: [
      {
        required: !isTeamLeader,
        message: '请输入最少提交人数',
        trigger: 'submit',
      },
      {
        validator: (rule, value, callback) => {
          if (isTeamLeader) {
            callback()
            return
          }
          // 基本验证：必须是数字且大于等于1
          if (value && isNaN(value)) {
            callback(new Error('最少提交人数必须大于等于1'))
          } else if (value && parseInt(value) < 1) {
            callback(new Error('最少提交人数必须大于等于1'))
          } else {
            callback()
          }
        },
        trigger: 'submit',
      },
    ],
    requirement: [{ required: false, message: '请选择要求', trigger: 'submit' }],
    basicRequirement: [{ required: false, message: '请输入其它要求', trigger: 'submit' }],
    workContent: [{ required: true, message: '请输入工作内容', trigger: 'submit' }],
    salary: [{ required: false, message: '请输入参考薪资', trigger: 'submit' }],
  }
}

const roles = ref([
  {
    roleType: '',
    personCount: '',
    minSubmitCount: '',
    requirement: '',
    basicRequirement: '',
    workContent: '',
    salary: '',
  },
])

// 控制验证是否启用的标志
const validationEnabled = ref(false)

const addRole = () => {
  roles.value.push({
    roleType: '',
    personCount: '',
    minSubmitCount: '',
    requirement: '',
    basicRequirement: '',
    workContent: '',
    salary: '',
  })
  // 等待DOM更新后，表单引用会自动通过ref回调函数设置
}

const removeRole = (index) => {
  roles.value.splice(index, 1)
  // 移除对应的表单引用
  roleFormRefs.value.splice(index, 1)

  // 重新计算可用选项，确保删除角色后其他角色可以重新选择被释放的角色类型
  nextTick(() => {
    roles.value = [...roles.value]
  })
}

// 获取指定角色卡片可用的角色选项
const getAvailableRoleOptions = (currentIndex) => {
  // 获取所有已选择的角色类型（排除当前角色）
  const selectedRoles = roles.value
    .map((role, index) => ({ type: role.roleType, index }))
    .filter((item) => item.type && item.index !== currentIndex)
    .map((item) => item.type)

  // 返回未被选择的角色选项
  return roleOptions.filter((option) => !selectedRoles.includes(option.value))
}

// 处理角色类型变更
const handleRoleTypeChange = (roleIndex) => {
  const currentRole = roles.value[roleIndex]

  // 如果角色变为"带队"，清空需求人数和最少提交人数
  if (currentRole.roleType === '带队') {
    currentRole.personCount = ''
    currentRole.minSubmitCount = ''
  }

  // 触发响应式更新，重新计算可用选项
  nextTick(() => {
    // 强制更新所有角色选择器的选项
    roles.value = [...roles.value]
  })
}

// 处理需求人数变更
const handlePersonCountChange = (roleIndex) => {
  const currentRole = roles.value[roleIndex]

  // 如果角色为"带队"，跳过处理
  if (currentRole.roleType === '带队') {
    return
  }

  const personCount = parseInt(currentRole.personCount)
  const minSubmitCount = parseInt(currentRole.minSubmitCount)

  // 如果需求人数小于最少提交人数，清空最少提交人数
  if (personCount && minSubmitCount && personCount > minSubmitCount) {
    currentRole.minSubmitCount = ''
  }

  // 触发响应式更新
  nextTick(() => {
    roles.value = [...roles.value]
  })
}

// 处理最少提交人数变更
const handleMinSubmitCountChange = (roleIndex) => {
  const currentRole = roles.value[roleIndex]

  // 如果角色为"带队"，跳过处理
  if (currentRole.roleType === '带队') {
    return
  }

  // 触发响应式更新
  nextTick(() => {
    roles.value = [...roles.value]
  })
}

// 保存项目信息到本地存储
const handleSaveProject = () => {
  try {
    // 准备要保存的项目数据
    const projectData = {
      basicInfo: {
        projectName: basicForm.value.projectName,
        activityTime: basicForm.value.activityTime,
        workLocation: basicForm.value.workLocation,
      },
      projectBelong: scheduleForm.value.projectBelong,
      roles: roles.value,
      userRowId: userRowId.value,
      saveTime: new Date().toISOString(),
    }

    // 保存到本地存储
    localStorage.setItem('savedProjectData', JSON.stringify(projectData))

    // 显示成功提示
    ElMessage({
      message: '项目信息已保存到本地！',
      type: 'success',
      duration: 3000,
    })

    console.log('项目数据已保存到本地存储:', projectData)
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage({
      message: '保存失败，请重试',
      type: 'error',
      duration: 3000,
    })
  }
}

const handleSubmit = async () => {
  try {
    // 校验基本信息表单
    await basicFormRef.value.validate()

    // 校验日程表单
    await scheduleFormRef.value.validate()

    // 校验所有角色表单
    for (let i = 0; i < roles.value.length; i++) {
      if (roleFormRefs.value[i]) {
        await roleFormRefs.value[i].validate()
      }
    }

    // 额外的业务逻辑验证：检查最少提交人数是否大于等于需求人数
    for (let i = 0; i < roles.value.length; i++) {
      const role = roles.value[i]
      // 如果角色为"带队"，跳过人数验证
      if (role.roleType === '带队') {
        continue
      }

      const personCount = parseInt(role.personCount)
      const minSubmitCount = parseInt(role.minSubmitCount)

      if (personCount && minSubmitCount && minSubmitCount < personCount) {
        throw new Error(`第${i + 1}个角色的最少提交人数应大于等于需求人数`)
      }
    }

    // 所有校验通过，准备提交数据
    const projectData = {
      projectName: basicForm.value.projectName,
      activityTime: basicForm.value.activityTime,
      workLocation: basicForm.value.workLocation,
      projectBelong: scheduleForm.value.projectBelong,
      roles: roles.value,
      userRowId: userRowId.value,
      submitTime: new Date().toISOString(),
      // 如果是编辑模式，添加项目的rowid
      ...(mode.value === 'edit' && editProject.value?.rowid
        ? { rowid: editProject.value.rowid }
        : {}),
    }

    console.log('准备提交的项目数据:', projectData)

    // 使用API服务提交数据
    if (mode.value === 'create') {
      const result = await apiService.submitProject(projectData)
      console.log('提交成功，返回结果:', result)
    } else {
      console.log('编辑项目:', projectData)

      const result = await apiService.submitProject(projectData)
      console.log('提交成功，返回结果:', result)
    }

    // 显示成功提示
    ElMessage({
      message: '项目信息提交成功！',
      type: 'success',
      duration: 3000,
    })

    // 提交成功后回到上一层
    setTimeout(() => {
      router.back()
    }, 1500)
  } catch (error) {
    console.error('提交失败:', error)

    // 显示错误提示
    ElMessage({
      message: error.message || '提交失败，请重试',
      type: 'error',
      duration: 4000,
    })
  }
}
</script>

<style scoped>
.customer-container {
  padding: 20px 20px 20px 40px;
  background-color: #ffffff;
  min-height: 100vh;
}

.create-project {
  max-width: 1200px;
  margin: 0;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  text-align: left;
}

/* 基本信息样式 */
.basic-info-wrapper {
  position: relative;
  margin-bottom: 60px;
}

.basic-info-card {
  background: #fdf9fa;
  margin-bottom: 20px;
}

.basic-info-card :deep(.el-card__body) {
  background: #fdf9fa;
}

.save-project-btn {
  position: absolute;
  left: 0;
  bottom: -50px;
  background: #ea4095 !important;
  border-color: #ea4095 !important;
}

.save-project-btn:hover {
  background: #d63384 !important;
  border-color: #d63384 !important;
}

/* 分隔线样式 */
.divider-line {
  height: 1px;
  background-color: #cfcfcf;
  margin-top: 70px;
  margin-bottom: 30px;
  width: 100%;
}

/* 角色信息样式 */
.roles-section {
  margin-bottom: 30px;
}

.role-card {
  background: linear-gradient(135deg, #faf5f9 0%, #fff9f9 50%, #f7f6fb 100%);
  height: 100%;
  box-shadow: none;
  border: 1px solid #e8e7e9;
}

.role-card :deep(.el-card__body) {
  background: linear-gradient(135deg, #faf5f9 0%, #fff9f9 50%, #f7f6fb 100%);
  height: 100%;
  box-shadow: none;
  padding: 15px !important;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.role-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.add-role-card {
  height: 100%;
  min-height: 350px;
  background: #f3f3f3;
  border: 2px dashed #dedede;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.add-role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 66, 66, 0);
}

.add-role-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
}

.add-role-card:hover .add-role-content {
  transform: scale(1.05);
}

.add-role-icon {
  font-size: 32px;
  color: #999;
  transition: all 0.3s ease;
}

.add-role-card:hover .add-role-icon {
  color: #ea4095;
  transform: scale(1.1);
}

.add-role-text {
  font-size: 16px;
  color: #999;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-role-card:hover .add-role-text {
  color: #ea4095;
}

/* 提交按钮样式 */
.submit-section {
  text-align: left;
}

.submit-btn {
  background: #ea4095 !important;
  border-color: #ea4095 !important;
  padding: 12px 40px;
  font-size: 14px;
  font-weight: bold;
}

.submit-btn:hover {
  background: #d63384 !important;
  border-color: #d63384 !important;
}

/* Element Plus 表单样式覆盖 */
:deep(.el-form-item__label) {
  color: #333;
  font-size: 14px;
  line-height: 32px;
}

/* 减少表单项之间的间距 */
:deep(.el-form-item) {
  margin-bottom: 12px !important;
}

/* 减少标签和输入框之间的间距 */
:deep(.el-form--label-left .el-form-item__label) {
  padding-right: 8px !important;
}

/* 针对角色卡片的表单项间距 */
.role-card :deep(.el-form-item) {
  margin-bottom: 15px !important;
}

/* 针对基本信息卡片的表单项间距 */
.basic-info-card :deep(.el-form-item) {
  margin-bottom: 15px !important;
}

/* 必填星号样式 - 将星号移到右上角 */
:deep(.el-form-item.is-required .el-form-item__label::after) {
  content: '*';
  color: #f56c6c;
  margin-left: 4px;
  position: relative;
  top: -8px;
  font-size: 12px;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '';
}

/* 完全覆盖Element Plus默认的必填星号样式 */
:deep(.el-form-item.is-required .el-form-item__label) {
  position: relative;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  display: none !important;
}

/* 紧凑的表单项样式 */
.compact-form-item {
  margin-bottom: 16px;
  position: relative;
  top: -25px;
}

.compact-form-item :deep(.el-form-item__label) {
  font-size: 12px;
  line-height: 20px;
  margin-bottom: 4px;
}

.compact-form-item :deep(.el-form-item__content) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

:deep(.el-input__wrapper) {
  background: #fefefe;
}

:deep(.el-textarea__inner) {
  background: #fefefe;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .basic-info-wrapper .el-col {
    margin-bottom: 20px;
  }

  .roles-section .el-col {
    margin-bottom: 20px;
  }

  .add-role-card {
    min-height: 250px;
  }
}
</style>
